package SSM.Chat.Utils;


import SSM.Chat.Dao.BookDao;
import SSM.Chat.Domain.Chat;
import SSM.Chat.Domain.ChatList;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@ServerEndpoint(value = "/websocket/{myWebsocket}", configurator =
        SpringConfigurator.class)
@Component

public class WebsocketController {

    //    @Autowired
    public static BookDao bookDao;


    public static Map<String, Session> SessionC =
            new HashMap<String, Session>();


    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session WebSocketsession;

    String myWebsocket = "";

    /**
     * 连接建立成功调用的方法
     *
     * @param myWebsocket
     */
    @OnOpen
//    public void onOpen(@PathParam("myWebsocket") String myWebsocket, Session session){
    public void onOpen(@PathParam("myWebsocket") String myWebsocket, Session session) {
        if (myWebsocket == null) {
            throw new RuntimeException();
        }
        Token token = new Token();
        String token1 = token.getToken(myWebsocket);
        if (token1.equals("401")) {
            throw new RuntimeException();
        }
//        List<Session> sessions = new ArrayList<>();
//        sessionMessage = session;
//        sessions.add(sessionMessage);
        SessionC.put(token1, session);

//        Request request1 = new Request();
//        String axios = request1.Axios(request);

//        //接收到发送消息的人员编号
//        myWebsocket = myWebsocket;
//        this.WebSocketsession = session;

//
//        if(clients.get(myWebsocket) != null){
//            sessions = clients.get(myWebsocket);
//            sessions.add(session);
//        }else{
//            sessions = new ArrayList<Session>();
//        }

//
//        //加入map中
//        webSocketSet.put(myWebsocket, this);
//        addOnlineCount();//在线数加1
    }

    /**
     * 收到客户端消息时触发
     *
     * @param myWebsocket
     * @param message
     * @return
     */
    @OnMessage
    public void onMessage(@PathParam("myWebsocket") String myWebsocket, String message) throws IOException {
        Token token = new Token();
        String token1 = token.getToken(myWebsocket);

        sendMessage(token1, message);
//        String Str="";
//        HashMap<String, String> map = new HashMap<>();
//        String[] split =
//                message.substring(1, message.length()-1).split(",");
//
//        for (int i = 0; i < split.length; i++) {
//
//
//            map.put(split[i].split(":")[0].substring(1,
//                            split[i].split(":")[0].length()-1),
//                    split[i].split(":")[1].substring(1,
//                            split[i].split(":")[1].length()-1));
//        }


//        return "Got your message ("+ message +").Thanks !";

    }

    /**
     * 异常时触发
     *
     * @param myWebsocket
     * @param throwable
     */
    @OnError
    public void onError(@PathParam("myWebsocket") String myWebsocket, Throwable throwable) {

    }

    /**
     * 关闭连接时触发
     *
     * @param myWebsocket
     */
    @OnClose
    public void onClose(@PathParam("myWebsocket") String myWebsocket) {
        Token token = new Token();
        String token1 = token.getToken(myWebsocket);
        // 用户退出时删除
        SessionC.remove(token1);

    }

    @Transactional(value = "To")
    public void sendMessage(String myWebsocket, String message) throws IOException {

        // 获取发信息的类
        Chat chat = JSON.parseObject(message, Chat.class);
        // 判断是否使心跳测试工具，当是心跳测试工具返回该信息
        if (chat.getChatType().equals("test")) {
            // 当确定是心跳检测使将原来信息直接返回
            Session session1 = SessionC.get(myWebsocket);
            session1.getBasicRemote().sendText(JSON.toJSONString(chat));
            return;
        }
        if (chat.getChatType().equals("Delete")) {
            // 当确定是心跳检测使将原来信息直接返回
            Session session1 = SessionC.get(myWebsocket);
            session1.getBasicRemote().sendText(JSON.toJSONString(chat));
            Session session2 =
                    SessionC.get(chat.getChatMailBoxOthers());
            if(session2!=null){
                session2.getBasicRemote().sendText(JSON.toJSONString(chat));
            }
            return;
        }
        // 获取聊天双方列表信息
        // 查询我与对方的聊天信息
        ChatList chatList = new ChatList();
        chatList.setChatListMailbox(myWebsocket);
        chatList.setChatListOthersMailbox(chat.getChatMailBoxOthers());
        ChatList chatList1 = bookDao.ChatListSelectMailbox(chatList);
        if (chatList1 == null) {
            // 添加聊天列表
            chatList.setChatLisOldList(chat.getChatText());
            chatList.setChatListTime(new Date());
            chatList.setChatListType(1);
            chatList.setChatListNew(2);
            chatList.setChatListChatType(chat.getChatType());
            bookDao.ChatListInformation(chatList);
        } else {
            // 当聊天列表存在的时候跟新聊天列表
            chatList1.setChatListNew(2);
            chatList1.setChatListType(1);
            chatList1.setChatListTime(new Date());
            chatList1.setChatLisOldList(chat.getChatText());
            chatList1.setChatListChatType(chat.getChatType());
            bookDao.ChatListUpdateType(chatList1);
        }
        ChatList chatLists = new ChatList();
        chatLists.setChatListMailbox(chat.getChatMailBoxOthers());
        chatLists.setChatListOthersMailbox(myWebsocket);
        ChatList chatList2 =
                bookDao.ChatListSelectMailbox(chatLists);
        if (chatList2 == null) {
            // 添加聊天列表
            chatLists.setChatLisOldList(chat.getChatText());
            chatLists.setChatListTime(new Date());
            chatLists.setChatListType(2);
            chatLists.setChatListNew(1);
            chatLists.setChatListChatType(chat.getChatType());
            bookDao.ChatListInformation(chatLists);
        } else {
            // 当聊天列表存在的时候跟新聊天列表
            chatList2.setChatListNew(1);
            chatList2.setChatListType(2);
            chatList2.setChatListTime(new Date());
            chatList2.setChatLisOldList(chat.getChatText());
            chatList2.setChatListChatType(chat.getChatType());
            bookDao.ChatListUpdateType(chatList2);
        }
        // 增加聊天信息
        chat.setChatMailbox(myWebsocket);
        chat.setChatTime(new Date());
        chat.setChatMailBoxOthersType(1);
        chat.setChatMailBoxType(1);
        bookDao.ChatInformation(chat);

        // 获取会话
        Session session = SessionC.get(chat.getChatMailBoxOthers());
        // 当会话不存在，标识用户不在线 ,用户不在线则不操作,用户在线则发送会话记录
        if (session != null) {
            session.getBasicRemote().sendText(JSON.toJSONString(chat));
        }
//        给自己发信息标识发送成功
        Session session1 = SessionC.get(myWebsocket);
        chat.setChatType("Info");
        session1.getBasicRemote().sendText(JSON.toJSONString(chat));


    }


    /**
     * 将数据传回客户端
     * 异步的方式
     *
     * @param myWebsocket
     * @param message
     */
//    public static void broadcast(String myWebsocket, String message) {
//        if (clients.containsKey(myWebsocket)) {
////            clients.get(myWebsocket).getAsyncRemote().sendText(message);
//
//            List<Session> sessions = clients.get(myWebsocket);
//            for (Session sess : sessions) {
//                sess.getAsyncRemote().sendText(message);
//            }
//        } else {
//            throw new NullPointerException("[" + myWebsocket + "]Connection does not exist");
//        }
//    }

//    public static synchronized int getOnlineCount() {
//        //返回在线人数
//        return onlineCount;
//    }

//    public static synchronized void addOnlineCount() {
//        //在线人数+1
//        WebsocketController.onlineCount++;
//    }

//    public static synchronized void subOnlineCount() {
//        //在线人数-1
//        WebsocketController.onlineCount--;
//    }


}
